package cs.asiainfo.config.dao.impl;

import cs.asiainfo.config.dao.MemberDao;
import cs.asiainfo.config.entity.MemberEntity;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import java.util.List;

/**
 * Created by many on 2016/8/9.
 * @author many
 * 会员DAO
 */
public class MemberDaoImpl implements MemberDao {
    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;

    /**
     * 新增会员
     */
    public Integer createMember(MemberEntity memberEntity) throws Exception{
        Configuration configuration = new Configuration().configure();
        serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();

        Integer memberId = (Integer)session.save(memberEntity);
        session.getTransaction().commit();

        return memberId;
    }

    /**
     * 查询会员信息
     */
    public MemberEntity qryMember(String memberName) throws Exception{
        Configuration configuration = new Configuration().configure();
        serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();

        StringBuilder sql = new StringBuilder("SELECT * FROM MEMBER WHERE 1 = 1");
        if(memberName != null){
            sql.append(" AND MEMBER_NAME = '" + memberName + "'");
        }
        Query query = session.createSQLQuery(sql.toString()).addEntity(MemberEntity.class);
        List<MemberEntity> result = query.list();

        if(result != null && result.size() == 1){
            return result.get(0);
        }
        else{
            return null;
        }
    }
}

